import {Vote} from '../types/vote'
import VoteList from '../views/vote_list';

//Vote 是对象的约束  Vote[]: 数组里放的是对象
interface IState{
    voteList:Vote[]
}

let initState:IState = {
    voteList:[]
}

function getIndex(data:Vote[],vid:number){
    return data.findIndex((item:Vote) => item.vid === vid);
}

export default (state=initState,action:any) => {
    switch (action.type) {
        case 'INIT_LIST':
            return {voteList:[...action.list]};
        case 'ADD_VOTE':{
            //action ： vid id curUser
            let index = getIndex(state.voteList,action.vid);
            //找投票对象
            let target = state.voteList[index];
            //添加票数
            target.items[action.id].num++;
            //添加投票者
            target.voteUsers.push(action.curUser);
            state.voteList[index] = {...target};
            return {voteList:[...state.voteList]}
        }
        default:
            return state;
    }
}